const path = require('path');
const fs = require('fs');

const {getLogInfo} = require("../service/log.service");

const { databaseError } = require('../constant/err.type');


class CommonController {

    async upload(ctx, next) {
        let {file} = ctx.request.files;
        if (file) {
            ctx.body = {
                code: 1,
                message: '文件上传成功！',
                result: {
                    file: path.basename(file.path)
                }
            };
        } else {
            ctx.app.emit('error', {
                code: '2',
                message: '文件上传异常！'
            }, ctx)
        }

    }

    // 获取预制的头像
    async getProfile(ctx, next) {
        // 遍历当前文件夹，批量注册路由
        let profiles = [];
        fs.readdirSync(path.join(__dirname, '../upload/profile')).forEach(fileName => {
            profiles.push({
                imageName: fileName,
                imageUrl: '/profile/' + fileName
            })
        });


        ctx.body = {
            code: 1,
            message: '初始头像获取成功！',
            result: {
                profiles: profiles
            }
        };


    }

    /**
     * 获取日志
     */
    async getLogInfo(ctx, next) {

        // 获取数据
        let {id, user_id, log_detail, user_ip, pageInfo} = ctx.request.query;
        // 操作数据库
        try {
            let res = await getLogInfo({id, user_id, log_detail, user_ip, pageInfo});
            if (res) {
                ctx.body = {
                    code: 1,
                    message: '日志列表查询成功！',
                    data: res
                }
            } else {
                ctx.app.emit('error', databaseError, ctx);
            }
        } catch (e) {
            ctx.app.emit('error', databaseError, ctx);
        }
    }
}

module.exports = new CommonController();